/**
 * 服务详情页面
 *
 * 这个页面展示了：
 * 1. 服务详细信息展示
 * 2. 服务特点列表
 * 3. 价格信息
 * 4. 相关服务推荐
 * 5. 联系咨询功能
 */
import React, { useEffect, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useService, useServices } from '@/hooks/useServices';
import { useContactInfo } from '@/hooks/useCompany';
import { useCreateMessage } from '@/hooks/useMessages';
import { toast } from 'sonner';

export default function ServiceDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [showContactModal, setShowContactModal] = useState(false);

  // 咨询表单状态
  const [consultForm, setConsultForm] = useState({
    name: '',
    phone: '',
    email: '',
    message: ''
  });

  // 获取服务详情
  const {
    data: service,
    isLoading,
    isError
  } = useService(parseInt(id || '0'));

  // 获取相关服务（同分类的其他服务）
  const {
    data: relatedServicesData
  } = useServices({
    category: service?.category,
    size: 4,
    active_only: true
  });

  // 获取联系信息
  const { data: contactInfo } = useContactInfo();

  // 创建留言
  const createMessage = useCreateMessage();

  // 错误处理
  useEffect(() => {
    if (isError) {
      toast.error('服务不存在或已下线');
      navigate('/services');
    }
  }, [isError, navigate]);

  // 格式化价格
  const formatPrice = (price?: number) => {
    if (!price) return '面议';
    if (price >= 10000) {
      return `${(price / 10000).toFixed(1)}万元起`;
    }
    return `${price.toLocaleString()}元起`;
  };

  // 解析服务特点
  const parseFeatures = (features?: string) => {
    if (!features) return [];
    try {
      return JSON.parse(features);
    } catch {
      return features.split(',').map(f => f.trim());
    }
  };

  // 处理咨询表单输入变化
  const handleConsultFormChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setConsultForm(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 提交咨询表单
  const handleConsultSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 验证必填字段
    if (!consultForm.name || !consultForm.phone || !consultForm.message) {
      toast.error('请填写所有必填字段');
      return;
    }

    try {
      await createMessage.mutateAsync({
        name: consultForm.name,
        phone: consultForm.phone,
        email: consultForm.email || undefined,
        subject: `服务咨询：${service?.name}`,
        message: consultForm.message
      });

      // 重置表单
      setConsultForm({
        name: '',
        phone: '',
        email: '',
        message: ''
      });

      setShowContactModal(false);
      toast.success('咨询信息已提交，我们会尽快与您联系！');
    } catch (error) {
      console.error('提交咨询失败:', error);
      toast.error('提交失败，请重试');
    }
  };

  // 联系咨询
  const handleContact = () => {
    setShowContactModal(true);
  };

  // 加载状态
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="container mx-auto px-4 py-8">
          <div className="max-w-4xl mx-auto">
            {/* 骨架屏 */}
            <div className="animate-pulse">
              <div className="h-4 bg-gray-200 rounded w-1/4 mb-6"></div>
              <div className="h-8 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="h-4 bg-gray-200 rounded w-1/2 mb-8"></div>
              <div className="h-64 bg-gray-200 rounded mb-8"></div>
              <div className="space-y-4">
                <div className="h-4 bg-gray-200 rounded"></div>
                <div className="h-4 bg-gray-200 rounded"></div>
                <div className="h-4 bg-gray-200 rounded w-5/6"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // 如果没有服务数据，返回空（错误处理会重定向）
  if (!service) {
    return null;
  }

  // 过滤相关服务（排除当前服务）
  const relatedServices = relatedServicesData?.items?.filter(item => item.id !== service.id) || [];
  const features = parseFeatures(service.features);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 面包屑导航 */}
      <div className="bg-white border-b">
        <div className="container mx-auto px-4 py-4">
          <nav className="flex items-center space-x-2 text-sm">
            <Link to="/" className="text-blue-600 hover:text-blue-800">
              首页
            </Link>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <Link to="/services" className="text-blue-600 hover:text-blue-800">
              服务项目
            </Link>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <span className="text-gray-600">{service.category}</span>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <span className="text-gray-900 truncate max-w-xs">{service.name}</span>
          </nav>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="max-w-6xl mx-auto">
          <div className="grid lg:grid-cols-3 gap-8">
            {/* 主要内容 */}
            <div className="lg:col-span-2">
              <div className="bg-white rounded-lg shadow-md overflow-hidden">
                {/* 服务头部 */}
                <div className="p-8">
                  <div className="flex items-center mb-4">
                    <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                      {service.category}
                    </span>
                    {service.is_featured && (
                      <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-orange-100 text-orange-800 ml-2">
                        <i className="fa-solid fa-star mr-1"></i>
                        推荐服务
                      </span>
                    )}
                  </div>

                  <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
                    {service.name}
                  </h1>

                  {service.description && (
                    <p className="text-lg text-gray-600 mb-6 leading-relaxed">
                      {service.description}
                    </p>
                  )}

                  {/* 价格信息 */}
                  <div className="bg-blue-50 border border-blue-200 rounded-lg p-6 mb-8">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="text-lg font-semibold text-blue-900 mb-2">服务价格</h3>
                        <p className="text-3xl font-bold text-blue-600">
                          {formatPrice(service.price)}
                        </p>
                        <p className="text-sm text-blue-700 mt-1">
                          具体价格根据项目规模和复杂程度确定
                        </p>
                      </div>
                      <div className="text-blue-600">
                        <i className="fa-solid fa-tags text-4xl"></i>
                      </div>
                    </div>
                  </div>

                  {/* 服务特点 */}
                  {features.length > 0 && (
                    <div className="mb-8">
                      <h3 className="text-xl font-semibold text-gray-900 mb-4">服务特点</h3>
                      <div className="grid md:grid-cols-2 gap-4">
                        {features.map((feature: string, index: number) => (
                          <div key={index} className="flex items-center">
                            <div className="w-2 h-2 bg-blue-600 rounded-full mr-3"></div>
                            <span className="text-gray-700">{feature}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>

                {/* 服务图标 */}
                {service.icon_url && !service.icon_url.startsWith('fa-') && (
                  <div className="px-8 mb-8">
                    <img
                      src={service.icon_url}
                      alt={service.name}
                      className="w-full h-64 object-cover rounded-lg"
                      onError={(e) => {
                        const target = e.target as HTMLImageElement;
                        target.style.display = 'none';
                      }}
                    />
                  </div>
                )}

                {/* 详细内容 */}
                {service.content && (
                  <div className="px-8 pb-8">
                    <h3 className="text-xl font-semibold text-gray-900 mb-4">详细介绍</h3>
                    <div
                      className="prose prose-lg max-w-none"
                      dangerouslySetInnerHTML={{ __html: service.content }}
                    />
                  </div>
                )}
              </div>
            </div>

            {/* 侧边栏 */}
            <div className="lg:col-span-1">
              {/* 联系咨询 */}
              <div className="bg-white rounded-lg shadow-md p-6 mb-6">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">
                  <i className="fa-solid fa-phone mr-2 text-blue-600"></i>
                  联系咨询
                </h3>

                {contactInfo && (
                  <div className="space-y-3 mb-6">
                    {contactInfo.phone && (
                      <div className="flex items-center">
                        <i className="fa-solid fa-phone text-gray-400 w-4"></i>
                        <a
                          href={`tel:${contactInfo.phone}`}
                          className="ml-3 text-blue-600 hover:text-blue-800"
                        >
                          {contactInfo.phone}
                        </a>
                      </div>
                    )}
                    {contactInfo.email && (
                      <div className="flex items-center">
                        <i className="fa-solid fa-envelope text-gray-400 w-4"></i>
                        <a
                          href={`mailto:${contactInfo.email}`}
                          className="ml-3 text-blue-600 hover:text-blue-800"
                        >
                          {contactInfo.email}
                        </a>
                      </div>
                    )}
                  </div>
                )}

                <button
                  type="button"
                  onClick={handleContact}
                  className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors font-medium"
                >
                  <i className="fa-solid fa-comments mr-2"></i>
                  立即咨询
                </button>
              </div>

              {/* 相关服务 */}
              {relatedServices.length > 0 && (
                <div className="bg-white rounded-lg shadow-md p-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">
                    <i className="fa-solid fa-cogs mr-2 text-blue-600"></i>
                    相关服务
                  </h3>
                  <div className="space-y-4">
                    {relatedServices.slice(0, 3).map((relatedService) => (
                      <Link
                        key={relatedService.id}
                        to={`/services/${relatedService.id}`}
                        className="block p-4 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-colors group"
                      >
                        <div className="flex items-center">
                          <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3 group-hover:bg-blue-200 transition-colors">
                            {relatedService.icon_url?.startsWith('fa-') ? (
                              <i className={`fa-solid ${relatedService.icon_url} text-blue-600`}></i>
                            ) : (
                              <i className="fa-solid fa-cog text-blue-600"></i>
                            )}
                          </div>
                          <div className="flex-1">
                            <h4 className="font-medium text-gray-900 group-hover:text-blue-600 transition-colors">
                              {relatedService.name}
                            </h4>
                            <p className="text-sm text-gray-600 mt-1">
                              {formatPrice(relatedService.price)}
                            </p>
                          </div>
                          <i className="fa-solid fa-chevron-right text-gray-400 group-hover:text-blue-600 transition-colors"></i>
                        </div>
                      </Link>
                    ))}
                  </div>

                  <div className="mt-4 pt-4 border-t">
                    <Link
                      to="/services"
                      className="text-blue-600 hover:text-blue-800 text-sm font-medium"
                    >
                      查看全部服务 <i className="fa-solid fa-arrow-right ml-1"></i>
                    </Link>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 返回按钮 */}
          <div className="text-center mt-8">
            <button
              type="button"
              onClick={() => navigate(-1)}
              className="inline-flex items-center px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
            >
              <i className="fa-solid fa-arrow-left mr-2"></i>
              返回上一页
            </button>
          </div>
        </div>
      </div>

      {/* 联系咨询模态框 */}
      {showContactModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-md w-full p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-gray-900">
                咨询服务：{service.name}
              </h3>
              <button
                type="button"
                onClick={() => setShowContactModal(false)}
                className="text-gray-400 hover:text-gray-600"
                aria-label="关闭对话框"
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>

            <form onSubmit={handleConsultSubmit}>
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    姓名 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={consultForm.name}
                    onChange={handleConsultFormChange}
                    required
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入您的姓名"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    电话 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="tel"
                    name="phone"
                    value={consultForm.phone}
                    onChange={handleConsultFormChange}
                    required
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入您的联系电话"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    邮箱
                  </label>
                  <input
                    type="email"
                    name="email"
                    value={consultForm.email}
                    onChange={handleConsultFormChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入您的邮箱"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    咨询内容 <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    name="message"
                    value={consultForm.message}
                    onChange={handleConsultFormChange}
                    required
                    rows={4}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                    placeholder="请详细描述您的需求..."
                  ></textarea>
                </div>
              </div>

              <div className="flex space-x-3 mt-6">
                <button
                  type="button"
                  onClick={() => setShowContactModal(false)}
                  className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  type="submit"
                  disabled={createMessage.isPending}
                  className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {createMessage.isPending ? (
                    <>
                      <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                      提交中...
                    </>
                  ) : (
                    '提交咨询'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}